var socketio = require('socket.io');
var io ;
var gustNumber = 1;
var nickName = {};
var nameUsed = [];
var currentRoom = {};
exports.listen = function(server){
    // 启动socket.io服务器搭载在http服务器上
    io = socketio.listen(server)
    io.serveClient('log level', 1);
    // 定义每一个用户连接的处理逻辑
    io.sockets.on('connection',function(socket){
        // 在用户连接上来时赋予其一个访客名称
        gustNumber = assignGuestName(socket,gustNumber,nickName,nameUsed)
        // 在用户连接上来是把他放入聊天室Lobby
        joinRoom(socket,'Lobby');
        // 处理用户的消息,
        handleMessageBroadcasting(socket,nickName);
        // 处理用户的更名
        handleNameChangeAttempts(socket,nickName,nameUsed);
        // 处理聊天室的创建
        handleRoomJoining(socket);
        // 用户发出请求时,向其提供已经被占用的聊天室列表
        socket.on('room',function(){
            socket.emit('room',io.sockets.manager.rooms);
        })
        // 定义用户断开连接后的清除逻辑
        handleClientDisconnection(socket,nickName,nameUsed);
    })
}
/**
 * 分配用户昵称
 * @param {用户} socket 
 * @param {用户id} gustNumber 
 * @param {用户列表} nickName 
 * @param {已占用用户列表} nameUsed 
 */
function assignGuestName(socket,gustNumber,nickName,nameUsed){
    // 生成新的昵称
    var name  = 'GUEST' + gustNumber;
    // 昵称+id拼接
    nickName[socket.id] = name;
    socket.emit('nameResult',{
        success:true,
        name:name
    })
    // 保存已占用昵称
    nameUsed.push(name);
    // 生成新的id
    return gustNumber + 1;
}
/**
 * 加入聊天室逻辑
 * @param {用户} socket 
 * @param {当前房间号} room 
 */
function joinRoom(socket,room){
    // 用户加入房间
    socket.join(room);
    // 记录当前id
    currentRoom[socket.id] = room;
    // 给用户返回加入结果
    socket.emit('joinResult',{room:room});
    // 通知其他用户新用户加入房间
    socket.broadcast.to(room).emit('message',{
        text:nickName[socket.id] + 'has joined' + room + '.'
    })
    // 显示当前房间有哪些用户
    var usersInRoom = io.sockets.clients(room);
    if(usersInRoom.length>1){
        var usersInRoomSummary = 'Users currently in ' + room + '.';
        for(var index in usersInRoom){
            var  userSocketId = usersInRoom[index].id;
            if(userSocketId!= socket.id){
                if(index>0){
                    usersInRoomSummary += ','
                }
                usersInRoomSummary += nickName[userSocketId]
            }
        }
        usersInRoomSummary += ".";
        // 返回给新进入的用户
        socket.emit('message',{text:usersInRoomSummary})
    }
}
/**
 * 用户更改名称逻辑
 * @param {用户} socket 
 * @param {用户列表} nickName 
 * @param {已占用用户名} nameUsed 
 */
function handleNameChangeAttempts(socket,nickName,nameUsed){
    socket.on('nameAttempt',function(name){
        if(name.indexOf('Guest') == 0){
            socket.emit('nameResult',{
                success:false,
                message:'Names cannot begin with Guest'
            })
        }else{
            if(nameUsed.indexOf(name) == -1){
                var previousName = nickName[socket.id];
                var previousNameIndex = nameUsed.indexOf(previousName);
                nameUsed.push(name);
                nickName[socket.id] = name;
                delete nameUsed[previousNameIndex];
                socket.emit('nameResult',{
                    success:false,
                    message:name
                })
                socket.broadcast.to(currentRoom[socket.id]).emit('message',{
                    text: previousName + 'is now know as' + name + "."
                })
            }else{
                socket.emit('nameResult',{
                    success:false,
                    message:'This name is already in use.'
                })
            }
        }
    })
}
/**
 * 发送聊天信息
 * @param {用户} socket 
 */
function handleMessageBroadcasting(socket){
    socket.on('message',function(message){
        socket.broadcast.to(message.room).emit('message',{
            text: nickName[socket.id] + ":" + message.text
        })
    })
}
/**
 *  创建房间
 * @param {用户} socket 
 */
function handleRoomJoining(socket){
    socket.on('join',function(room){
        socket.leave(currentRoom[socket.id]);
        joinRoom(socket,room.newRoom)
    })
}
/**
 * 用户断开连接
 * @param {用户} socket 
 */
function handleClientDisconnection(socket){
    socket.on('disconnect',function(){
        var nameIndex = nameUsed.indexOf(nickName[socket.id])
        delete nameUsed[nameIndex];
        delete nickName[socket.id]
    })
}